<template>
    <div class="indices-card">
        <div class="card-header">
            <h3>中国指数</h3>
        </div>
        <div class="card-body">
            <el-table
                :data="indicesData"
                style="width: 100%"
                :show-header="true"
                :header-cell-style="tableStyle.headerCellStyle"
                :cell-style="tableStyle.cellStyle"
                size="small"
                :height="'auto'"
                border
            >
                <el-table-column prop="indexName" label="指数名称" />
                <el-table-column
                    prop="latestPrice"
                    label="最新价"
                    align="right"
                >
                    <template #default="{ row }">
                        <span>{{ row.latestPrice }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 只有总条数 > pageSize 时才显示分页 -->
            <div v-if="totalCount > pageSize" class="pagination-controls">
                <div class="pagination-buttons">
                    <el-button
                        size="small"
                        type="text"
                        @click="prevPage"
                        :disabled="currentPage === 1"
                    >
                    </el-button>

                    <div class="pagination-indicator">
                        <span
                            v-for="index in totalPages"
                            :key="index"
                            :class="{
                                active: currentPage === index,
                                clickable: true,
                            }"
                            class="dot"
                            @click="handlePageChange(index)"
                        ></span>
                    </div>

                    <el-button
                        size="small"
                        type="text"
                        @click="nextPage"
                        :disabled="currentPage === totalPages"
                    >
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, computed, onMounted, onBeforeUnmount, inject } from 'vue';
    import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
    import { getIndices } from '../api/api.js';
    import { tableStyle } from '../utils/tableConfig.js';

    // 默认页码和页面大小
    const currentPage = ref(1);
    const pageSize = ref(5);
    const totalCount = ref(0);
    const indicesData = ref([]);

    //  添加自动翻页定时器变量
    let autoSwitchTimer = null;

    // 计算总页数，最少1页
    const totalPages = computed(() => {
        return totalCount.value <= pageSize.value
            ? 1
            : Math.ceil(totalCount.value / pageSize.value);
    });

    const getIndicesData = async (
        page = currentPage.value,
        size = pageSize.value
    ) => {
        try {
            const res = await getIndices({
                page,
                size,
            });

            if (res.code === '200' && res.message === 'success') {
                // 处理标准分页格式返回
                if (res.data && res.data.content) {
                    indicesData.value = res.data.content;
                    totalCount.value = res.data.totalElements || 0;
                    // 如果API返回了pageSize，更新当前的pageSize值
                    if (res.data.pageSize) {
                        pageSize.value = res.data.pageSize;
                    }
                    // 更新当前页码
                    if (res.data.currentPage) {
                        currentPage.value = res.data.currentPage;
                    }
                }
                // 处理非分页数组
                else if (Array.isArray(res.data)) {
                    indicesData.value = res.data;
                    totalCount.value = res.data.length;
                }
                // 处理单个对象
                else {
                    indicesData.value = [res.data];
                    totalCount.value = 1;
                }
            } else {
                console.error('获取指数数据失败:', res.message);
                indicesData.value = [];
                totalCount.value = 0;
            }
        } catch (error) {
            console.error('获取指数数据失败:', error);
            indicesData.value = [];
            totalCount.value = 0;
        }
    };

    // 翻页函数
    const nextPage = () => {
        // 循环翻页逻辑
        if (currentPage.value < totalPages.value) {
            currentPage.value++;
        } else {
            currentPage.value = 1; // 循环到第一页
        }
        getIndicesData(currentPage.value, pageSize.value);
    };

    const prevPage = () => {
        // 循环翻页逻辑
        if (currentPage.value > 1) {
            currentPage.value--;
        } else {
            currentPage.value = totalPages.value; // 循环到最后一页
        }
        getIndicesData(currentPage.value, pageSize.value);
    };

    // 页面切换函数
    const handlePageChange = pageNumber => {
        if (pageNumber >= 1 && pageNumber <= totalPages.value) {
            // 停止自动翻页（如果用户手动点击了页码）
            if (autoSwitchTimer) {
                clearInterval(autoSwitchTimer);
                autoSwitchTimer = null;
            }

            currentPage.value = pageNumber;
            getIndicesData(currentPage.value, pageSize.value);

            // 手动翻页后延时重启自动翻页
            setTimeout(() => {
                startAutoSwitch();
            }, 10000); // 10秒后重新启动自动翻页
        }
    };

    // 在 ChinaIndices.vue 中添加
    const shouldPauseUpdates = inject('shouldPauseUpdates', ref(false));

    // 修改自动翻页函数
    const startAutoSwitch = () => {
        // 清除可能存在的定时器
        if (autoSwitchTimer) {
            clearInterval(autoSwitchTimer);
            autoSwitchTimer = null;
        }

        // 仅当有多页时启动自动翻页
        if (totalPages.value > 1) {
            autoSwitchTimer = setInterval(() => {
                // 只有在不暂停更新时才执行翻页
                if (!shouldPauseUpdates.value) {
                    nextPage();
                }
            }, 5000);
        }
    };

    // 修改数据获取函数
    const fetchDataWithCheck = () => {
        // 只有在不暂停更新时才获取新数据
        if (!shouldPauseUpdates.value) {
            getIndicesData(currentPage.value, pageSize.value);
        }
    };

    // 设置定期刷新数据（比如每30秒）
    let dataRefreshTimer = null;
    // 添加响应式页面大小设置函数
    const adjustPageSizeByScreenHeight = () => {
        const height = window.innerHeight;
        const oldSize = pageSize.value; // 保存旧值用于比较

        // 更精细的屏幕高度识别
        if (height >= 1800) {
            pageSize.value = 15; // 超高分辨率屏幕(4K)
        } else if (height >= 1300) {
            pageSize.value = 11; // 高分辨率大屏
        } else if (height >= 1000) {
            pageSize.value = 9; // 中等屏幕
        } else if (height >= 768) {
            pageSize.value = 5; // 适合当前786px高度
        } else if (height >= 600) {
            pageSize.value = 4; // 小屏幕
        } else {
            pageSize.value = 3; // 极小屏幕
        }

        console.log(
            `当前屏幕高度: ${height}px, 设置每页显示条数: ${pageSize.value}`
        );

        // 仅当页面大小确实变化时才重新加载数据
        if (oldSize !== pageSize.value) {
            console.log(
                `页面大小从 ${oldSize} 变为 ${pageSize.value}，重新加载数据`
            );
            currentPage.value = 1; // 重置为第一页
            getIndicesData(1, pageSize.value);
        }
    };
    // 添加防抖函数
    const debounce = (fn, delay) => {
        let timer = null;
        return function (...args) {
            if (timer) clearTimeout(timer);
            timer = setTimeout(() => {
                fn.apply(this, args);
            }, delay);
        };
    };

    // 创建防抖包装的调整函数
    const debouncedAdjustPageSize = debounce(adjustPageSizeByScreenHeight, 300);

    // 保存事件监听器引用
    const resizeListener = ref(null);

    onMounted(() => {
        // 首先调整页面大小
        adjustPageSizeByScreenHeight();
        getIndicesData();

        // 添加窗口大小变化监听
        window.addEventListener('resize', debouncedAdjustPageSize);
        resizeListener.value = debouncedAdjustPageSize;

        // 设置定期刷新数据
        dataRefreshTimer = setInterval(() => {
            fetchDataWithCheck();
        }, 30000); // 30秒刷新一次

        setTimeout(() => {
            startAutoSwitch();
        }, 1000);
    });

    onBeforeUnmount(() => {
        // 移除窗口大小变化监听
        if (resizeListener.value) {
            window.removeEventListener('resize', resizeListener.value);
        }

        if (autoSwitchTimer) {
            clearInterval(autoSwitchTimer);
            autoSwitchTimer = null;
        }
        if (dataRefreshTimer) {
            clearInterval(dataRefreshTimer);
            dataRefreshTimer = null;
        }
    });
</script>

<style scoped>
    @import '../assets/css/style.css';

    .indices-card {
        background-color: #001e4a;
        border-radius: 5px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        height: 100%;
        display: flex;
        flex-direction: column;
    }

    /* 分页控制样式 - 修改为固定位置 */
    .pagination-controls {
        display: flex;
        justify-content: center;
        padding: 10px 0 5px;
        margin-top: auto;
        /* 确保始终在底部 */
    }

    .pagination-buttons {
        display: flex;
        align-items: center;
    }

    .pagination-indicator {
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 10px;
    }

    .dot {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: rgba(140, 214, 255, 0.3);
        margin: 0 4px;
        transition: all 0.3s ease;
    }

    .dot.active {
        background-color: #8cd6ff;
        transform: scale(1.2);
    }

    .dot.clickable {
        cursor: pointer;
    }

    .dot.clickable:hover {
        background-color: rgba(140, 214, 255, 0.8);
    }

    /* 响应式设计 */
    @media (min-height: 1200px) {
        .card-header h3 {
            font-size: 22px;
        }

        .card-body {
            padding: 20px;
        }
    }

    @media (min-height: 1800px) {
        .card-header h3 {
            font-size: 26px;
        }

        .card-body {
            padding: 25px;
        }
    }
</style>
